package com.cn.integration.business.paycenter.strategy;

import com.cn.common.enums.PayChannelCodeEnum;
import com.cn.common.utils.exception.ServiceException;
import com.cn.common.utils.text.StringUtil;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class StrategyContext implements InitializingBean,ApplicationContextAware{

    private ApplicationContext applicationContext;

    private final Map<String, PayService> strategyMap = new ConcurrentHashMap<>();

    @Override
    public void afterPropertiesSet(){
        applicationContext.getBeansOfType(PayService.class).values().stream().forEach(v -> strategyMap.put(v.getPayChannelCode(),v));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public PayService getPayMethod(String payChannelCode){
        String payName = PayChannelCodeEnum.getNameByCode(payChannelCode);
        if(StringUtil.isEmpty(payName)){
            throw new ServiceException("支付通道错误");
        }
        return strategyMap.get(payChannelCode);
    }

}
